'use client';

import React, { useState, useRef, useEffect } from 'react';
import { Card, Input, Button, Avatar, Typography, Spin, message, Image, Pagination, Select, Drawer, List, Skeleton, Empty } from 'antd';
import { SendOutlined, LoadingOutlined, UserOutlined, RobotOutlined, PictureOutlined } from '@ant-design/icons';
import AdminLayout from '../AdminLayout';
import { handleApiResponse } from '@/utils/domUtils';
import styles from './AIChat.module.scss';
import './global-preview.css';
import { useRouter } from 'next/navigation';

const { TextArea } = Input;
const { Text } = Typography;

interface Message {
  id: string;
  role: 'user' | 'assistant';
  content: string;
  timestamp: Date;
  images?: string[];
  generatedPrompt?: string;
  generatedNegativePrompt?: string;
}

export default function AIChatPage() {
  const [messages, setMessages] = useState<Message[]>([]);
  const [inputValue, setInputValue] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [streamingMessage, setStreamingMessage] = useState('');
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const abortControllerRef = useRef<AbortController | null>(null);

  // 新增：历史记录相关状态
  const [sessionId, setSessionId] = useState<string>('default');
  const [historyVisible, setHistoryVisible] = useState<boolean>(false);
  const [historyLoading, setHistoryLoading] = useState<boolean>(false);
  const [historyPage, setHistoryPage] = useState<number>(1);
  const [historyPageSize, setHistoryPageSize] = useState<number>(20);
  const [historyTotal, setHistoryTotal] = useState<number>(0);
  const [historyItems, setHistoryItems] = useState<Message[]>([]);

  const router = useRouter();

  // 检测是否包含图片生成关键词
  const isImageGenerationRequest = (text: string): boolean => {
    const imageKeywords = [
      '生成图片', '画图', '画一张', '生成一张', '创建图片', '制作图片',
      '画', '绘制', '生成', '创建', '制作', '图片', '图像', '照片',
      'generate image', 'create image', 'draw', 'paint', 'picture', 'photo'
    ];
    
    return imageKeywords.some(keyword => 
      text.toLowerCase().includes(keyword.toLowerCase())
    );
  };

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages, streamingMessage]);

  useEffect(() => {
    fetch('/api/license/status').then(async (res) => {
      const result = await res.json();
      if (result.status !== 200) {
        router.push('/');
      }
    }).catch(() => {
      router.push('/');
    });
  }, []);

  // 打开历史侧栏时加载
  useEffect(() => {
    if (historyVisible) {
      void fetchHistory(historyPage, historyPageSize);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [historyVisible, sessionId]);

  const fetchHistory = async (page: number, pageSize: number) => {
    try {
      setHistoryLoading(true);
      const params = new URLSearchParams({ sessionId, page: String(page), pageSize: String(pageSize) });
      const res = await fetch(`/api/ai-chat/history?${params.toString()}`);
      const data = await res.json();
      if (!data.success) throw new Error(data.error || '获取历史失败');
      // API 返回的 data 为按时间倒序（最新在前）
      const items: Message[] = (data.data || []).map((m: any) => ({
        id: m.id || m._id || m.createdAt || String(Date.now()),
        role: m.role,
        content: m.content,
        timestamp: new Date(m.createdAt || Date.now()),
      }));
      setHistoryItems(items);
      setHistoryTotal(data.pagination?.total || items.length);
      setHistoryPage(data.pagination?.page || page);
      setHistoryPageSize(data.pagination?.pageSize || pageSize);
    } catch (e: any) {
      message.error(e?.message || '获取历史失败');
    } finally {
      setHistoryLoading(false);
    }
  };

  const handleLoadHistoryToChat = (item?: Message) => {
    // 如果传入单条，插入；如果不传入，加载当前历史页作为对话内容
    if (item) {
      setMessages(prev => [...prev, item]);
      return;
    }
    // 将当前页的历史（时间倒序）按时间正序展示
    const sorted = [...historyItems].sort((a, b) => (a.timestamp as any) - (b.timestamp as any));
    setMessages(sorted);
    setHistoryVisible(false);
  };

  const handleHistoryPageChange = (page: number, pageSize?: number) => {
    setHistoryPage(page);
    if (pageSize && pageSize !== historyPageSize) setHistoryPageSize(pageSize);
    void fetchHistory(page, pageSize || historyPageSize);
  };

  const saveMessagesToHistory = async (msgs: Pick<Message, 'role' | 'content'>[]) => {
    try {
      await fetch('/api/ai-chat/history', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ sessionId, messages: msgs.map(m => ({ role: m.role, content: m.content })) }),
      });
    } catch (e) {
      // 静默失败即可
      console.warn('保存历史失败', e);
    }
  };

  const handleSendMessage = async () => {
    if (!inputValue.trim() || isLoading) return;

    const userMessage: Message = {
      id: Date.now().toString(),
      role: 'user',
      content: inputValue.trim(),
      timestamp: new Date(),
    };

    setMessages(prev => [...prev, userMessage]);
    // 保存用户消息到历史
    void saveMessagesToHistory([{ role: 'user', content: userMessage.content }]);

    setInputValue('');
    setIsLoading(true);

    // 检测是否为图片生成请求
    if (isImageGenerationRequest(inputValue.trim())) {
      await handleImageGeneration(inputValue.trim());
    } else {
      await handleTextChat(inputValue.trim());
    }
  };

  const handleImageGeneration = async (userInput: string) => {
    try {
      const response = await fetch('/api/ai-chat/generate-image', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ userInput }),
      });

      const data = await handleApiResponse(response);

      if (data.success && data.images && data.images.length > 0) {
        const assistantMessage: Message = {
          id: (Date.now() + 1).toString(),
          role: 'assistant',
          content: `根据您的描述，我已经生成了图片。\n\n正向提示词：${data.generatedPrompt}\n反向提示词：${data.generatedNegativePrompt}`,
          timestamp: new Date(),
          images: data.images,
          generatedPrompt: data.generatedPrompt,
          generatedNegativePrompt: data.generatedNegativePrompt,
        };

        setMessages(prev => [...prev, assistantMessage]);
        // 保存助手消息
        void saveMessagesToHistory([{ role: 'assistant', content: assistantMessage.content }]);

        message.success('图片生成成功！');
      } else {
        throw new Error(data.error || '图片生成失败');
      }
    } catch (error: any) {
      console.error('图片生成错误:', error);
      const errorMessage: Message = {
        id: (Date.now() + 1).toString(),
        role: 'assistant',
        content: `抱歉，图片生成失败：${error.message}`,
        timestamp: new Date(),
      };
      setMessages(prev => [...prev, errorMessage]);
      // 保存错误信息为助手消息（可选）
      void saveMessagesToHistory([{ role: 'assistant', content: errorMessage.content }]);
      message.error('图片生成失败，请重试');
    } finally {
      setIsLoading(false);
    }
  };

  const handleTextChat = async (userInput: string) => {
    try {
      abortControllerRef.current = new AbortController();

      const response = await fetch('/api/ai-chat', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          messages: [
            ...messages.map(msg => ({
              role: msg.role,
              content: msg.content
            })),
            { role: 'user', content: userInput }
          ]
        }),
        signal: abortControllerRef.current.signal,
      });

      if (!response.ok) {
        throw new Error('聊天请求失败');
      }

      const reader = response.body?.getReader();
      if (!reader) {
        throw new Error('无法读取响应流');
      }

      let accumulatedContent = '';
      setStreamingMessage('');

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        const chunk = new TextDecoder().decode(value);
        const lines = chunk.split('\n');

        for (const line of lines) {
          if (line.startsWith('data: ')) {
            const data = line.slice(6);
            if (data === '[DONE]') {
              // 流式响应结束
              const assistantMessage: Message = {
                id: (Date.now() + 1).toString(),
                role: 'assistant',
                content: accumulatedContent,
                timestamp: new Date(),
              };
              setMessages(prev => [...prev, assistantMessage]);
              // 保存助手消息
              void saveMessagesToHistory([{ role: 'assistant', content: assistantMessage.content }]);
              setStreamingMessage('');
              return;
            }

            try {
              const parsed = JSON.parse(data);
              if (parsed.choices && parsed.choices[0]) {
                const deltaContent = parsed.choices[0]?.delta?.content;
                const textContent = parsed.choices[0]?.text;
                const messageContent = parsed.choices[0]?.message?.content;
                const genericContent = parsed.content;

                const contentPiece = deltaContent ?? textContent ?? messageContent ?? genericContent;

                if (typeof contentPiece === 'string' && contentPiece.length > 0) {
                  accumulatedContent += contentPiece;
                  setStreamingMessage(accumulatedContent);
                }
              }
            } catch (e) {
              // 忽略解析错误
            }
          }
        }
      }
    } catch (error: any) {
      if (error.name === 'AbortError') {
        console.log('请求被取消');
        return;
      }
      console.error('聊天错误:', error);
      const errorMessage: Message = {
        id: (Date.now() + 1).toString(),
        role: 'assistant',
        content: `抱歉，发生了错误：${error.message}`,
        timestamp: new Date(),
      };
      setMessages(prev => [...prev, errorMessage]);
      void saveMessagesToHistory([{ role: 'assistant', content: errorMessage.content }]);
      message.error('聊天失败，请重试');
    } finally {
      setIsLoading(false);
      setStreamingMessage('');
    }
  };

  const handleStopGeneration = () => {
    if (abortControllerRef.current) {
      abortControllerRef.current.abort();
      abortControllerRef.current = null;
    }
    setIsLoading(false);
    setStreamingMessage('');
  };

  const handleClearChat = () => {
    setMessages([]);
    setStreamingMessage('');
    message.success('对话已清空');
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  // 快速操作数据
  const quickActions = [
    {
      id: 'common-questions',
      title: '常见问题',
      icon: '❓',
      items: [
        { text: '如何生成高质量的图片？', prompt: '请告诉我如何生成高质量的图片，有什么技巧吗？' },
        { text: '什么是提示词工程？', prompt: '什么是提示词工程？如何写出好的提示词？' },
        { text: '图片生成的参数说明', prompt: '请详细解释图片生成中各个参数的作用和设置建议' },
        { text: '如何优化生成速度？', prompt: '如何优化AI图片生成的速度和效率？' }
      ]
    },
    {
      id: 'art-styles',
      title: '艺术风格',
      icon: '🎨',
      items: [
        { text: '写实风格', prompt: '生成一幅写实风格的人物肖像画，细节丰富，光影自然' },
        { text: '动漫风格', prompt: '生成一张动漫风格的可爱女孩，大眼睛，彩色头发' },
        { text: '油画风格', prompt: '生成一幅印象派油画风格的风景画，色彩浓郁，笔触明显' },
        { text: '水彩风格', prompt: '生成一幅清新的水彩风格花朵，淡雅色彩，柔和边缘' }
      ]
    },
    {
      id: 'image-themes',
      title: '主题场景',
      icon: '🌅',
      items: [
        { text: '科幻未来', prompt: '生成一个充满科技感的未来城市场景，霓虹灯，飞行汽车' },
        { text: '自然风光', prompt: '生成一幅壮丽的山川湖泊自然风光，晨雾缭绕，阳光透射' },
        { text: '古典建筑', prompt: '生成一座典雅的古典欧式建筑，精美雕刻，历史感强' },
        { text: '抽象艺术', prompt: '生成一幅色彩斑斓的抽象艺术作品，几何图形，现代感强' }
      ]
    },
    {
      id: 'character-types',
      title: '角色类型', 
      icon: '👤',
      items: [
        { text: '可爱宠物', prompt: '生成一只超级可爱的小猫咪，毛茸茸，大眼睛，卡通风格' },
        { text: '奇幻生物', prompt: '生成一个神秘的奇幻生物，龙的特征，华丽翅膀，魔法光效' },
        { text: '机器人', prompt: '生成一个未来感十足的机器人，金属质感，发光眼睛，科技细节' },
        { text: '超级英雄', prompt: '生成一个威武的超级英雄，炫酷服装，能量光效，动态姿势' }
      ]
    }
  ];

  // 处理快速操作点击
  const handleQuickAction = (prompt: string) => {
    setInputValue(prompt);
  };

  const renderMessage = (message: Message) => (
    <div key={message.id} className={`${styles.messageItem} ${message.role === 'user' ? styles.userMessage : styles.assistantMessage}`}>
      <div className={styles.messageContent}>
        <div className={styles.messageHeader}>
          <Avatar
            icon={message.role === 'user' ? <UserOutlined /> : <RobotOutlined />}
            className={styles.messageAvatar}
          />
          <Text className={styles.messageRole}>
            {message.role === 'user' ? '用户' : 'AI助手'}
          </Text>
          <Text className={styles.messageTime}>
            {message.timestamp.toLocaleTimeString()}
          </Text>
        </div>
        <div className={styles.messageText}>
          {message.content}
          {message.role === 'assistant' && message.images && message.images.length > 0 && (
            <div className={styles.imageContainer}>
              {message.images.map((image, index) => (
                <div key={index} className={styles.imageWrapper}>
                  <Image
                    src={`data:image/png;base64,${image}`}
                    alt={`生成的图片 ${index + 1}`}
                    className={styles.generatedImage}
                    preview={{
                      mask: '点击查看大图',
                      maskClassName: styles.imagePreviewMask,
                    }}
                    placeholder={
                      <div className={styles.imagePlaceholder}>
                        <Spin size="small" />
                        <span>图片加载中...</span>
                      </div>
                    }
                  />
                  <div className={styles.imageInfo}>
                    <Text className={styles.imagePrompt}>
                      <strong>正向提示词：</strong>{message.generatedPrompt}
                    </Text>
                    <Text className={styles.imagePrompt}>
                      <strong>反向提示词：</strong>{message.generatedNegativePrompt}
                    </Text>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );

  return (
    <AdminLayout>
      <div className={styles.chatContainer}>
        <Card className={styles.chatCard}>
          {/* 顶部工具栏：历史按钮 + 会话选择 */}
          <div className={styles.historyToolbar}>
            <div className={styles.toolbarLeft}>
              <Button onClick={() => setHistoryVisible(true)} type="default">聊天历史</Button>
            </div>
            <div className={styles.toolbarRight}>
              <span className={styles.toolbarLabel}>会话:</span>
              <Select
                value={sessionId}
                onChange={(val) => setSessionId(val)}
                style={{ width: 160 }}
                options={[
                  { label: '默认会话', value: 'default' },
                  // 预留更多会话，后续可从接口拉取
                ]}
              />
            </div>
          </div>

          {/* 快速操作卡片 */}
          <div className={styles.quickActionsBar}>
            {quickActions.map(group => (
              <div key={group.id} className={styles.quickGroup}>
                <div className={styles.quickGroupHeader}>
                  <span className={styles.quickGroupIcon}>{group.icon}</span>
                  <span className={styles.quickGroupTitle}>{group.title}</span>
                </div>
                <div className={styles.quickItems}>
                  {group.items.map((item, idx) => (
                    <Button
                      key={idx}
                      className={styles.quickItem}
                      size="small"
                      onClick={() => handleQuickAction(item.prompt)}
                      title={item.prompt}
                    >
                      {item.text}
                    </Button>
                  ))}
                </div>
              </div>
            ))}
          </div>
          <div className={styles.messagesContainer}>
            {messages.length === 0 ? (
              <div className={styles.emptyState}>
                <div className={styles.emptyIcon}>🤖</div>
                <div className={styles.emptyText}>
                  开始与AI助手对话吧！<br />
                  您可以描述想要生成的图片，我会为您创建精美的图像。
                </div>
              </div>
            ) : (
              <>
                {messages.map(renderMessage)}
                {streamingMessage && (
                  <div className={`${styles.messageItem} ${styles.assistantMessage}`}>
                    <div className={styles.messageContent}>
                      <div className={styles.messageHeader}>
                        <Avatar
                          icon={<RobotOutlined />}
                          className={styles.messageAvatar}
                        />
                        <Text className={styles.messageRole}>AI助手</Text>
                        <Text className={styles.messageTime}>
                          {new Date().toLocaleTimeString()}
                        </Text>
                      </div>
                      <div className={styles.messageText}>
                        {streamingMessage}
                        <span className={styles.cursor}>|</span>
                      </div>
                    </div>
                  </div>
                )}
                
                {/* AI助手思考中的进度提示 */}
                {isLoading && !streamingMessage && (
                  <div className={`${styles.messageItem} ${styles.assistantMessage}`}>
                    <div className={styles.messageContent}>
                      <div className={styles.messageHeader}>
                        <Avatar
                          icon={<RobotOutlined />}
                          className={styles.messageAvatar}
                        />
                        <Text className={styles.messageRole}>AI助手</Text>
                        <Text className={styles.messageTime}>
                          {new Date().toLocaleTimeString()}
                        </Text>
                      </div>
                      <div className={styles.messageText}>
                        <div className={styles.thinkingIndicator}>
                          <Spin size="small" />
                          <span className={styles.thinkingText}>AI正在思考中...</span>
                        </div>
                      </div>
                    </div>
                  </div>
                )}
              </>
            )}
            <div ref={messagesEndRef} />
          </div>

          {/* 输入区域 */}
          <div className={styles.inputContainer}>
                          <div className={styles.inputWrapper}>
                <TextArea
                  value={inputValue}
                  onChange={(e) => setInputValue(e.target.value)}
                  onKeyPress={handleKeyPress}
                  placeholder="输入您的问题或描述想要生成的图片...&#10;支持多行输入，Shift+Enter换行，Enter发送&#10;包含'生成图片'、'画图'等关键词将自动生成图片"
                  autoSize={{ minRows: 3, maxRows: 6 }}
                  disabled={isLoading}
                  className={styles.messageInput}
                  showCount
                  maxLength={2000}
                />
                <div className={styles.inputActions}>
                  {isLoading ? (
                    <Button
                      type="primary"
                      danger
                      icon={<LoadingOutlined />}
                      onClick={handleStopGeneration}
                      className={styles.stopButton}
                    >
                      停止生成
                    </Button>
                  ) : (
                    <Button
                      type="primary"
                      icon={isImageGenerationRequest(inputValue) ? <PictureOutlined /> : <SendOutlined />}
                      onClick={handleSendMessage}
                      disabled={!inputValue.trim()}
                      className={styles.sendButton}
                    >
                      {isImageGenerationRequest(inputValue) ? '生成图片' : '发送'}
                    </Button>
                  )}
                </div>
              </div>
            
            <div className={styles.chatActions}>
              <div className={styles.inputHint}>
                <span className={styles.hintIcon}>💡</span>
                <span className={styles.hintText}>
                  Enter 发送消息 | Shift+Enter 换行 | 包含图片关键词自动生成图片 | 最多2000字符
                </span>
              </div>
              <Button
                type="text"
                onClick={handleClearChat}
                disabled={messages.length === 0 && !isLoading}
                className={styles.clearButton}
              >
                清空对话
              </Button>
            </div>
          </div>
        </Card>
      </div>

      {/* 历史抽屉 */}
      <Drawer
        title="聊天历史"
        placement="right"
        width={520}
        open={historyVisible}
        onClose={() => setHistoryVisible(false)}
        className={styles.historyDrawer}
      >
        <div className={styles.historyHeader}>
          <Button type="primary" onClick={() => handleLoadHistoryToChat()}>
            将当前页载入到对话
          </Button>
        </div>

        <div className={styles.historyListWrapper}>
          {historyLoading ? (
            <List
              dataSource={Array.from({ length: 8 }, (_, idx) => ({ id: `sk-${idx}` }))}
              rowKey="id"
              renderItem={(_, idx) => (
                <List.Item>
                  <List.Item.Meta
                    avatar={<Skeleton.Avatar active size="small" shape="circle" />}
                    title={<Skeleton.Input active size="small" style={{ width: 120 }} />}
                    description={<Skeleton active paragraph={{ rows: 2 }} title={false} />}
                  />
                </List.Item>
              )}
            />
          ) : historyItems.length === 0 ? (
            <Empty description="暂无历史记录" />
          ) : (
            <List
              dataSource={historyItems}
              rowKey="id"
              renderItem={(item) => (
                <List.Item
                  actions={[
                    <Button key="insert" type="link" onClick={() => handleLoadHistoryToChat(item)}>插入此消息</Button>
                  ]}
                >
                  <List.Item.Meta
                    avatar={<Avatar icon={item.role === 'user' ? <UserOutlined /> : <RobotOutlined />} />}
                    title={`${item.role === 'user' ? '用户' : 'AI助手'} · ${item.timestamp.toLocaleString()}`}
                    description={<div className={styles.historyItemContent}>{item.content}</div>}
                  />
                </List.Item>
              )}
            />
          )}
        </div>

        <div className={styles.historyPagination}>
          <Pagination
            current={historyPage}
            pageSize={historyPageSize}
            total={historyTotal}
            size="small"
            onChange={handleHistoryPageChange}
            showSizeChanger
          />
        </div>
      </Drawer>
    </AdminLayout>
  );
}
